﻿$(function () {
    toastr.options.positionClass = 'toast-bottom-center';

    // 自定义验证
    var checkMaxCount = (rule, value, callback) => {
        if (!value) {
            return callback(new Error('请填写最大检查人数'))
        }
        if (!Number.isInteger(Number(value))) {
            return callback(new Error('必须为整数'));
        }
        callback();
    }

    var checkDayInWeeks = (rule,value,callback)=> {
        if (!value) {
            return callback(new Error("请选择要在一周的哪些些天批量创建号池计划"))
        }
        if (value.length === 0) {
            return callback(new Error("请选择要在一周的哪些些天批量创建号池计划"))
        }
        callback();
    }

    var vm = new Vue({
        el: '#app',
        components: {
            'plan-pool': PlanPoolComponent // 局部注册组件
        },
        data: {
            // 角色与权限
            planPoolPermission: true, // 能进到本页面，就是true
            planPoolCreatePermission: false,
            planPoolEditPermission: false,
            planPoolDeletePermission: false,
            planPoolDisablePermission: false,
            planPoolBatchCreatePermission: false,
            planPoolClearPermission:false,

            schedule: null,
            deviceType: null,
            department: null,
            dialogVisible: false,
            batchCreatVisible: false,
            dialogTitle: '新建号池计划',
            detailTitleWeekDay: null,
            detailTitleInterval:null,
            actionType: '新建',
            tableData: [],
            tableKey:0,
            selectedCells: [],
            dayInWeeks: [
                {
                    value: 0,
                    label:'星期一'
                },
                {
                    value: 1,
                    label: '星期二'
                },
                {
                    value: 2,
                    label: '星期三'
                },
                {
                    value: 3,
                    label: '星期四'
                },
                {
                    value: 4,
                    label: '星期五'
                },
                {
                    value: 5,
                    label: '星期六'
                },
                {
                    value: 6,
                    label: '星期日'
                }

            ],

            formLabelWidth: '80px',

            // 当前排班计划表
            planPool: {
                id: null,
                isActive: true,
                timeIntervalId: null,
                maxCount: 10,
                allowOverFlow: true,
                overFlowCount:0,
                scheduleId: null,
                dayInWeek: 0,
                refName:null
            },

            // 批量生成模型
            batchModel: {
                startTime: null,
                endTime: null,
                dayInWeeks: [],
                maxCount: 10,
                allowOverFlow: true,
                overFlowCount: 0
            },

            valueFormat: 'HH:mm',
            timePickerFormat: 'HH:mm a',

            // 批量 TimePickerOption
            batchStartTimePockerOption: {
                selectableRange: '00:00:00-23:59:59',
                format: 'HH:mm a'
            },
            batchEndTimePickerOption: {
                selectableRange: '00:00:00-23:59:59',
                format: 'HH:mm a'
            },

            // 验证规则
            rules: {
                maxCount: [
                    { validator: checkMaxCount, trigger: 'blur' }
                ]
            },

            batchRules: {
                startTime: [
                    { required: true, message: '请输入开始时间', trigger: 'blur' }
                ],
                endTime: [
                    { required: true, message: '请输入结束时间', trigger: 'blur' }
                ],
                maxCount: [
                    { required: true, message: '请输入最大数量', trigger: 'blur' },
                    { validator: checkMaxCount, trigger: 'blur' }
                ],
                dayInWeeks: [
                    { required: true, message: '不能为空，请选择', trigger: 'blur' },
                    { validator: checkDayInWeeks,trigger: 'blur' }
                ]
            }
        },
        computed: {

        },
        watch: {

        },
        methods: {

            // 获取排班计划
            getSchedule() {
                var vm = this;
                return new Promise(resolve => {
                    var sid = window.utils.getQuery('sid');
                    if (!sid) {
                        abp.message.error('未获取到sid参数');
                    }
                    else {
                        abp.ajax({
                            type: 'get',
                            url: `/api/schedule/get?id=${sid}`
                        }).then(res => {
                            if (res.code === 0) {
                                vm.schedule = res.data;
                                vm.department = vm.schedule.department;
                                vm.deviceType = vm.schedule.deviceType;
                                resolve();
                            }
                        })
                    }
                });
            },

            // 选中号池计划改变
            cellSelectedChange(cell) {
                var vm = this;
                if (cell.value) { // 选中的
                    if (vm.selectedCells.indexOf(cell) === -1) {
                        vm.selectedCells.push(cell);
                    }
                }
                else { // 取消选中
                    var index = vm.selectedCells.indexOf(cell)
                    if (index !== -1) {
                        vm.selectedCells.splice(index,1);
                    }
                }
            },

            startTimeChange(val) {
                var vm = this;

                if (vm.planPool.endTime) {
                    vm.planPool.name = `${vm.planPool.startTime} - ${vm.planPool.endTime}`
                } else {
                    vm.planPool.name = `${vm.planPool.startTime} -`
                }
                var str = `${val}:00 - 23:59:59`
                vm.endTimePickerOption = {
                    selectableRange: str,
                    format: 'HH:mm a'
                }
            },

            endTimeChange(val) {
                var vm = this;
                if (vm.planPool.startTime) {
                    vm.planPool.name = `${vm.planPool.startTime} - ${vm.planPool.endTime}`
                }
                else {
                    vm.planPool.name = `-${vm.planPool.endTime}`
                }
                var str = `00:00:00 - ${val}:59`
                vm.startTimePickerOption = {
                    selectableRange: str,
                    format: 'HH:mm a'
                }
            },

            // 批量对话框开始时间改变
            batchStartTimeChange(val) {
                var vm = this;
                var str = `${val}:00 - 23:59:59`
                vm.batchEndTimePickerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 批量对话框结束时间改变
            batchEndTimeChange(val) {
                var vm = this;
                var str = `00:00:00 - ${val}:59`
                vm.batchStartTimePockerOption = {
                    selectableRange: str,
                    format: vm.timePickerFormat
                }
            },

            // 加载表格数据(只在初始化时执行一次)
            loadTableData() {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/plan-pool/get-tab-data?sid=${vm.schedule.id}`
                    }).then(res => {
                        if (res.code === 0) {
                            vm.tableData = res.data;
                            if (vm.tableData.length === 0) {
                                abp.message.error('无预约时段，请先配置预约时段！');
                            }
                            resolve();
                        }
                    });
                })
            },

            // 显示新建检查项目对话框
            showCreate(params) {
                var vm = this;
                vm.dialogTitle = '创建排班计划';
                vm.actionType = '创建';
                vm.dialogVisible = true;
                vm.detailTitleWeekDay = vm.dayInWeeks[params.dayInWeek].label;
                vm.detailTitleInterval = vm.tableData.filter(x => x.id == params.timeIntervalId)[0].name;
                vm.planPool.isActive = true;
                vm.planPool.maxCount = 10;
                vm.planPool.allowOverFlow = true;
                vm.planPool.overFlowCount = 0;
                vm.planPool.scheduleId = params.scheduleId;
                vm.planPool.timeIntervalId = params.timeIntervalId;
                vm.planPool.dayInWeek = params.dayInWeek;
                vm.planPool.refName = params.refName;
            },

            // 新建提交
            submitCreate() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        vm.planPool.scheduleId = vm.schedule.id;
                        abp.ajax({
                            type: 'post',
                            url: `/api/plan-pool/submit-create?sid=${vm.schedule.id}`,
                            data: JSON.stringify(vm.planPool)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.$refs[vm.planPool.refName][0].loadData();
                                vm.resetForm();
                            }
                        });
                    }
                });
            },

            // 打开编辑窗口
            showEdit(planPool) {
                var vm = this;
                vm.dialogTitle = '编辑排班计划';
                vm.actionType = '编辑';
                vm.loadDetail(planPool.id).then((res) => {
                    vm.planPool = res
                    vm.planPool.refName = planPool.refName;
                    vm.detailTitleWeekDay = vm.dayInWeeks[res.dayInWeek].label;
                    vm.detailTitleInterval = vm.tableData.filter(x => x.id == res.timeIntervalId)[0].name;
                    vm.dialogVisible = true;
                })
            },

            // 编辑提交
            submitEdit() {
                var vm = this;
                vm.$refs['dialogForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/plan-pool/submit-edit`,
                            data: JSON.stringify(vm.planPool)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.$refs[vm.planPool.refName][0].loadData();
                                vm.resetForm();
                            }
                        })
                    }
                });
            },

            save() {
                var vm = this;
                if (vm.actionType.includes('编辑')) {
                    vm.submitEdit();
                }
                else {
                    vm.submitCreate();
                }
            },

            // 打开批量生成对话框
            showBatchCreate() {
                var vm = this;
                vm.batchCreatVisible = true;
            },

            // 批量生成
            batchCreate() {
                var vm = this;
                vm.$refs['batchForm'].validate((vaild) => {
                    if (vaild) {
                        abp.ajax({
                            type: 'post',
                            url: `/api/plan-pool/batch-create?sid=${vm.schedule.id}`,
                            data: JSON.stringify(vm.batchModel)
                        }).then(res => {
                            if (res.code === 0) {
                                abp.notify.success(res.msg);
                                vm.currentPage = 1;
                                vm.tableKey++;
                                vm.resetBatchForm();
                            }
                        });
                    }
                });
            },

            // 获取号池计划详情
            loadDetail(id) {
                var vm = this;
                return new Promise(resolve => {
                    abp.ajax({
                        type: 'get',
                        url: `/api/plan-pool/get?id=${id}`
                    }).then((res) => {
                        if (res.code === 0) {
                            vm.planPool = res.data;
                            resolve(res.data);
                        }
                    })
                });
            },

            // 加载当前权限
            loadPermission() {
                var vm = this;
                return new Promise((resolve, reject) => {
                    if (abp.auth.isGranted('AppointManagerGroup.PlanPool')) { // 检查项目管理权限
                        vm.planPoolPermission = true;
                        if (abp.auth.isGranted('AppointManagerGroup.PlanPool.Create')) {// 新建检查项目权限
                            vm.planPoolCreatePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.PlanPool.Edit')) { // 编辑检查项目权限
                            vm.planPoolEditPermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.PlanPool.Delete')) { // 删除检查项目权限
                            vm.planPoolDeletePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.PlanPool.Disable')) { // 同步数据权限
                            vm.planPoolDisablePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.PlanPool.BatchCreate')) {
                            vm.planPoolBatchCreatePermission = true;
                        }
                        if (abp.auth.isGranted('AppointManagerGroup.PlanPool.Clear')) {
                            vm.planPoolClearPermission = true;
                        }
                    }
                    resolve();
                });
            },

            disableToggle(row) {
                var vm = this;
                var confirmStr = '禁用预约时段';
                if (row.isActive) {
                    confirmStr = '启用预约时段';
                }
                abp.message.confirm(confirmStr)
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'get',
                                url: `/api/plan-pool/toggle-disable?id=${id}`
                            }).then((res) => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.loadTableData();
                                }
                            })
                        }
                    })
            },

            // 删除号池计划（单个）
            deletePlanPool(params) {
                var vm = this;
                abp.message.confirm('删除号池计划')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'delete',
                                url: `/api/plan-pool/delete?id=${params.id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.$refs[params.refName][0].loadData();
                                }
                            })
                        }
                    })
            },

            // 删除多个
            deleteMany() {
                var vm = this;
                if (vm.selectedCells.length === 0) {
                    abp.notify.error('请选中号池计划！');
                }
                else {
                    var idList = vm.selectedCells.map(item => item.id);
                    abp.message.confirm('批量删除选中号池计划。')
                        .then(confirmed => {
                            if (confirmed) {
                                abp.ajax({
                                    type: 'post',
                                    url: `/api/plan-pool/delete-many`,
                                    data: JSON.stringify(idList)
                                }).then(res => {
                                    if (res.code === 0) {
                                        abp.notify.success(res.msg);
                                        vm.selectedCells.forEach(cell => {
                                            vm.$refs[cell.refName][0].loadData();
                                        })
                                    }
                                });
                            }
                        })
                }
            },

            // 号池计划清空
            deleteAll() {
                var vm = this;
                abp.message.confirm('清空当前排班下所有好吃计划？')
                    .then(confirmed => {
                        if (confirmed) {
                            abp.ajax({
                                type: 'delete',
                                url: `/api/plan-pool/delete-all?sid=${vm.schedule.id}`
                            }).then(res => {
                                if (res.code === 0) {
                                    abp.notify.success(res.msg);
                                    vm.tableKey++;
                                }
                            })
                        }
                    })
            },

            // 表单重置
            resetForm() {
                var vm = this;
                vm.$refs['dialogForm'].resetFields();
                vm.dialogVisible = false;
                Object.keys(vm.planPool).forEach(key => {
                    vm.planPool[key] = null;
                });
            },

            // 批量生成 表单重置
            resetBatchForm() {
                var vm = this;
                vm.$refs['batchForm'].resetFields();
                vm.batchCreatVisible = false;
                vm.batchModel.startTime = null;
                vm.batchModel.endTime = null ;
                vm.batchModel.allowOverFlow = true;
                vm.batchModel.maxCount = 10;
                vm.batchModel.dayInWeeks = [];
                vm.batchStartTimePockerOption = {
                    selectableRange: '00:00:00-23:59:59',
                    format: 'HH:mm:ss a'
                };
                vm.batchEndTimePickerOption = {
                    selectableRange: '00:00:00-23:59:59',
                    format: 'HH:mm:ss a'
                };
            },

            // 初始化
            init() {
                var vm = this;
                vm.loadPermission()
                    .then(() => {
                        vm.getSchedule().then(() => {
                            vm.loadTableData();
                        });
                    });
            }
        },
        created() {
            var vm = this;
            vm.init();
        },
        mounted() {
        }
    });
});